package com.java.basis.thread.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池使用完毕为何必须 shutdown()?
 * 由于内存不足,线程池无法创建新的线程而抛出OutOfMemoryError错误，此时主线程线程池还未执行shutdown()方法，于是抛出异常后主线程结束，
 * shutdown()方法无法执行，导致已经创建的线程在任务结束后挂起，无法结束。而只要‘非守护线程’未结束,进程就不会结束，所以出现了非常多阻塞进程。
 * @author wangning
 * @date 2023/4/26 17:42
 */
public class TestThreadPool {

    public static void main(String[] args) {
        ExecutorService fixedThreadPool = null;
        try {
            fixedThreadPool = Executors.newFixedThreadPool(20);
            for (int i = 0; i < 20; i++) {
                fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName());
                    }
                });
            }
            System.out.println("main-thread");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert fixedThreadPool != null;
            fixedThreadPool.shutdown();
        }
    }

}
